package com.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.user.domain.po.TbUser;
import com.user.mapper.UserLoginMapper;
import com.user.service.UserLoginService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.user.utils.JwtTool;

@Service
@RequiredArgsConstructor
public class UserLoginServiceImpl extends ServiceImpl<UserLoginMapper, TbUser> implements UserLoginService {
    private final UserLoginMapper userLoginMapper;
    private final JwtTool jwtTool;

    @Override
    public String login(String mobile, String pwd) {
        QueryWrapper<TbUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TbUser::getMobile, mobile).like(TbUser::getPwd, pwd);
        TbUser tbUser = userLoginMapper.selectOne(queryWrapper);
        if (ObjectUtils.isEmpty(tbUser)) {
            return "密码或手机号输入错误";
        }
        //生成token
        String token = jwtTool.createToken(tbUser.getId());

        return token;
    }

    @Override
    public TbUser query(Long id) {
       if(id==null){
           return null;
       }
        TbUser tbUser = userLoginMapper.selectById(id);
        return tbUser;
    }

    @Override
    public String post(TbUser tbUser) {
        try {
            userLoginMapper.insert(tbUser);
        } catch (Exception e) {
            return "添加失败";
        }
        return "添加成功";
    }

    @Override
    public String UserPut(TbUser tbUser) {
        try {
            userLoginMapper.updateById(tbUser);
        } catch (Exception e) {
            return "修改失败";
        }
        return "修改成功";
    }

    @Override
    public String delete(Long id) {
        try {
            userLoginMapper.deleteById(id);
        } catch (Exception e) {
            return "删除失败";
        }
        return "删除成功";
    }
}
